package ch03.acXml.ac3;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @auth 邝志豪
 * @date 2024/1/9 14:15
 */
public class CGLIBProxyFactory implements MethodInterceptor {
    //创建代理对象的方法，参数为目标对象，返回值为代理对象
    public Object createProxy(Object target) {
        //创建Enhancer对象，用于生成代理对象
        Enhancer enhancer = new Enhancer();
        //设置父类为目标对象的类
        enhancer.setSuperclass(target.getClass());
        //设置回调为当前对象，即实现MethodInterceptor接口的对象
        enhancer.setCallback(this);
        //使用create方法创建代理对象
        return enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        LogUtils.logBefore(method.getName());
        Object result=methodProxy.invokeSuper(o,objects);
        LogUtils.logAfter(method.getName());
        return result;
    }
}
